let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: '',
    user: {},
    paidCourses: [],
    unpaidCourses: [],
    currentType: 'paid',
    pageNum: 1,
    pageSize: 6,
    pages: 0,
    isLoading: false,
    hasMoreData: true
  },

  changeType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      currentType: type,
      pageNum: 1, 
      paidCourses: [],
      unpaidCourses: [],
      hasMoreData: true
    }, () => {
      this.getMyCourse();
    });
  },

goToPay(e) {
  const courseId = e.currentTarget.dataset.id;
  const userId = this.data.user.id;
  
  if (!courseId) {
    wx.showToast({
      title: '获取课程信息失败',
      icon: 'none'
    });
    return;
  }
  
  if (!userId) {
    wx.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  
  wx.request({
    url: this.data.url + 'courseCollect', 
    method: 'PUT', 
    data: {
      userId: userId,
      courseId: courseId,
      status: '已支付'
    },
    success: (resp) => {
      if (resp.data && resp.data.success) {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1500
        });
        
        setTimeout(() => {
          this.setData({
            pageNum: 1,
            paidCourses: [],
            unpaidCourses: [],
            hasMoreData: true
          }, () => {
           this.onLoad()
          });
        }, 1500);
      } else {
        wx.showToast({
          title: resp.data.msg || '支付失败',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      console.error('支付接口调用失败', err);
      wx.showToast({
        title: '网络错误，支付失败',
        icon: 'none'
      });
    },
    complete: () => {
      wx.hideLoading();
    }
  });
},
  getMyCourse() {
    if (!this.data.user.id || this.data.isLoading || !this.data.hasMoreData) return;

    this.setData({ isLoading: true });
    wx.showLoading({ title: "正在加载中..." });
    const status = this.data.currentType === 'paid' ? '已支付' : '未支付';

    wx.request({
      url: this.data.url + 'courseCollect/getCourseCollectByUserId',
      method: "GET",
      data: {
        userId: this.data.user.id,
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize,
        status: status
      },
      success: (resp) => {
        const respData = resp.data.data || {};
        const newCourses = respData.list || [];
        console.log(resp.data.data.list)
        if (this.data.currentType === 'paid') {
          this.setData({
            paidCourses: [...this.data.paidCourses, ...newCourses]
          });
        } else {
          this.setData({
            unpaidCourses: [...this.data.unpaidCourses, ...newCourses]
          });
        }

        this.setData({
          pages: respData.pages || 0,
          hasMoreData: this.data.pageNum < (respData.pages || 0)
        });
      },
      fail: (err) => {
        console.error('获取课程列表失败', err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
        this.setData({ isLoading: false });
        wx.stopPullDownRefresh();
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      url: app.globalData.url,
      user: wx.getStorageSync('user') || {}
    });
    if (this.data.user.id) {
      this.getMyCourse();
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const currentUser = wx.getStorageSync('user') || {};
    if (currentUser.id && currentUser.id !== this.data.user.id) {
      this.setData({
        user: currentUser,
        pageNum: 1,
        paidCourses: [],
        unpaidCourses: [],
        hasMoreData: true
      }, () => {
        this.getMyCourse();
      });
    }
  },

  /**
   * 页面下拉刷新
   */
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      paidCourses: [],
      unpaidCourses: [],
      hasMoreData: true
    }, () => {
      this.getMyCourse();
    });
  },

  /**
   * 页面上拉触底
   */
  onReachBottom() {
    if (this.data.isLoading || !this.data.hasMoreData) return;

    this.setData({
      pageNum: this.data.pageNum + 1
    }, () => {
      this.getMyCourse();
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的课程',
      path: '/pages/course/myCourse/myCourse'
    };
  }
})
